<template>
  <el-dialog title="出库修改" :visible.sync="visible" :center="true" width="70%" :close-on-click-modal="false">
    <el-row>
      <el-col>单位:{{ company }}</el-col>
      <el-col>日期:{{ date }}</el-col>
    </el-row>
    <el-table :data="outboundData" :border="true" size="mini">
      <el-table-column label="序号" type="index" min-width="5%"></el-table-column>
      <el-table-column label="名称" min-width="15%" prop="name">
      </el-table-column>
      <el-table-column label="物料编码" min-width="10%">
        <template slot-scope="scope">
          <el-input v-model="scope.row.code" size="mini"
                    @change="handleCodeChange(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格/型号" min-width="30%" prop="model">
      </el-table-column>
      <el-table-column label="单位" min-width="5%" prop="unit">
      </el-table-column>
      <el-table-column label="数量" min-width="5%">
        <template slot-scope="scope">
          <el-input v-model="scope.row.number" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="项目号" min-width="20%">
        <template slot-scope="scope">
          <el-input v-model="scope.row.project" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="出库地点" prop="positionName" v-if=false>
      </el-table-column>
      <el-table-column header-align="center" min-width="10%" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="deleteOutboundRow(scope.$index)"
                     icon="el-icon-delete"></el-button>
          <el-button type="text" size="mini" @click="addOutboundRow(scope.$index)"
                     icon="el-icon-plus"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col>领用人:{{ recipient }}</el-col>
      <el-col>审核:</el-col>
      <el-col>出库:</el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-input type="textarea" size="mini" rows="3" placeholder="请填写处理意见"
                  v-model="outboundComment"></el-input>
      </el-col>
    </el-row>
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>审批记录</span>
      </div>
      <el-timeline style="padding: 0 !important;">
        <el-timeline-item
            v-for="(item, index) in processCommentArray"
            :key="index"
            :timestamp=item.taskName placement="top">
          <div class="timelineDiv">
            <h4>{{ item.userId }}&nbsp;:&nbsp;{{ item.message }}</h4>
            <h4>{{ formatTime(item.time) }}</h4>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    <el-row>
      <el-col :span="24">
        <el-input type="textarea" size="mini" rows="3" placeholder="请填写处理意见"
                  v-model="approvalComment"></el-input>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" size="mini">提交</el-button>
      <el-button type="primary" @click="cancle" size="mini">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import moment from "moment";

export default {
  name: "ModifyOutbound",
  data() {
    return {
      company: '赛福斯特',
      date: this.formatTime(new Date()),
      outboundData: [],
      processCommentArray: [],
      approvalComment: '',
      outboundComment: '',
      recipient: '',
    }
  },
  computed: {
    visible: {
      get() {
        return this.$store.state.isVisible;
      },
      set(value) {
        this.$store.commit('setIsVisible', value);
      }
    },
  },
  watch: {
    visible(newVal) {
      console.log('Visible changed to: ', newVal);
    }
  },
  methods: {
    formatTime(time) {
      return moment(time).format('YYYY/MM/DD HH:mm:ss');
    },
    handleCodeChange(row) {
      const code = row.code
      this.$http.get(`/material/selectApplyOutboundByCode/${code}`).then((response) => {
        if (response.data.code == 1) {
          const applyOutboundVO = response.data.data
          console.log(applyOutboundVO)
          row.name = applyOutboundVO.name
          row.model = applyOutboundVO.model
          row.unit = applyOutboundVO.unit
        } else {
          this.$message.error("未查询到对应物资信息，请检查code编码");
        }
      });
    },
    addOutboundRow() {
      this.outboundData.push({
        id: null,
        name: '',
        code: '',
        model: '',
        unit: '',
        number: '',
        project: '',
        positionName: ''
      })
    },
    deleteOutboundRow(index) {
      const row = this.outboundData[index];
      if (!row || !row.id) {
        this.outboundData.splice(index, 1);
        return;
      }
      this.$confirm('确定删除该行物资吗？', '提示', {type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消'}).then(() => {
        this.$http.delete(`/material/outbound/${row.id}`).then(response => {
          if (response.data.code === 1) {
            this.$message.success('删除成功');
            this.outboundData.splice(index, 1);
          } else {
            this.$message.error('删除失败');
          }
        })
      })
      if (this.outboundData.length === 0) {
        this.outboundData.push({});
      }
    },
    submit() {
      const outboundMaterialDTOS = this.outboundData
      console.log(JSON.stringify(outboundMaterialDTOS, null, 2))
      this.$http.put("/material/outbound/update_process_outbound", outboundMaterialDTOS).then((response) => {
        if (response.data.code == 1) {
          this.$message.success("出库单更新成功，请等待复审")
        } else {
          this.$message.error("出库单更新失败");
        }
      });
      this.visible = false
    },
    cancle() {
      this.visible = false
    }
  },
  mounted() {
    const taskId = this.$store.state.taskId
    this.$http.get(`/material/outbound/${taskId}`).then((response) => {
      if (response.data.code == 1) {
        this.outboundData = response.data.data.map(item => ({
          ...item,
          totalPriceTax: (Math.round(item.unitPriceBeforeTax * (1 + item.taxRate) * item.number * 100) / 100).toFixed(2),
          amountBeforeTax: (Math.round(item.unitPriceBeforeTax * item.number * 100) / 100).toFixed(2)
        }));
        this.recipient = this.outboundData.length > 0 ? this.outboundData[0].recipient : null
        console.log(this.outboundData)
        this.visible = true
      } else {
        console.log("获取申请出库数据失败")
      }
    })
    this.$http.get(`/history/comment/${taskId}`).then((response) => {
      if (response.data.code == 1) {
        this.processCommentArray = response.data.data
      }
    })
  }
}
</script>